﻿Imports System.Globalization

Public Class frmDevolucion

    Private Sub frmNotaRemision_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        dgvdetalle.AutoGenerateColumns = False
        btnImprimir.Visible = False

        cboEstado.SelectedIndex = 0

        oiml.CargarCombos(cboMotivo, "motivo", "idMotivoStock", controllerStock.get_motivos_stock_devolucion(oiml.dbConn, True))
        oiml.CargarCombos(cboDeposito, "descripcion", "idDeposito", controllerStock.get_depositos(oiml.dbConn, 0, "", "", True))

        CargarNotasRemision()
    End Sub

    Dim controller As New ControllerSigeco.controller_compras
    Dim controllerVtas As New ControllerSigeco.controller_ventas
    Dim controllerStock As New ControllerSigeco.controller_stock

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private _idMercaderiaLote As Integer = 0

    Public Property codMercaderiaLote() As Integer
        Get
            Return _idMercaderiaLote
        End Get
        Set(ByVal value As Integer)
            _idMercaderiaLote = value
        End Set
    End Property

    Private _codNotaRemision As Integer = 0

    Public Property codNotaRemision() As Integer
        Get
            Return _codNotaRemision
        End Get
        Set(ByVal value As Integer)
            _codNotaRemision = value
        End Set
    End Property

    Private _codProveedor As Integer = 0

    Public Property codProveedor() As Integer
        Get
            Return _codProveedor
        End Get
        Set(ByVal value As Integer)
            _codProveedor = value
        End Set
    End Property

    Private _codCliente As Integer = 0

    Public Property codCliente() As Integer
        Get
            Return _codCliente
        End Get
        Set(ByVal value As Integer)
            _codCliente = value
        End Set
    End Property

    Private _codMercaderia As Integer = 0

    Public Property codMercaderia() As Integer
        Get
            Return _codMercaderia
        End Get
        Set(ByVal value As Integer)
            _codMercaderia = value
        End Set
    End Property

    Private _codMercaderiaDetalle As Integer = 0

    Public Property codMercaderiaDetalle() As Integer
        Get
            Return _codMercaderiaDetalle
        End Get
        Set(ByVal value As Integer)
            _codMercaderiaDetalle = value
        End Set
    End Property

    Private _codCompra As Integer = 0

    Public Property codCompra() As Integer
        Get
            Return _codCompra
        End Get
        Set(ByVal value As Integer)
            _codCompra = value
        End Set
    End Property

    Private _codVenta As Integer = 0

    Public Property codVenta() As Integer
        Get
            Return _codVenta
        End Get
        Set(ByVal value As Integer)
            _codVenta = value
        End Set
    End Property

    Private m_frmBusMercaderia As frmMercaderiaBuscador
    Public Property frmBusMercaderia() As frmMercaderiaBuscador
        Get
            Return m_frmBusMercaderia
        End Get
        Set(ByVal value As frmMercaderiaBuscador)
            m_frmBusMercaderia = value
        End Set
    End Property

    Private m_frmBusProveedor As frmProveedorBuscador
    Public Property frmBusProveedor() As frmProveedorBuscador
        Get
            Return m_frmBusProveedor
        End Get
        Set(ByVal value As frmProveedorBuscador)
            m_frmBusProveedor = value
        End Set
    End Property

    Private m_frmBusCliente As frmClienteBuscador
    Public Property frmBusCliente() As frmClienteBuscador
        Get
            Return m_frmBusCliente
        End Get
        Set(ByVal value As frmClienteBuscador)
            m_frmBusCliente = value
        End Set
    End Property

    Private Sub btnBuscProveedor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscProveedor.Click

        codVenta = 0
        codCompra = 0
        txtFactura.Text = ""

        frmBusProveedor = New frmProveedorBuscador
        frmBusProveedor.ShowDialog()
        txtProveedor.Text = frmBusProveedor.ProveedorDesc
        codProveedor = frmBusProveedor.codProveedor

        If codProveedor > 0 Then
            btnBuscMercaderia.Focus()
        End If

    End Sub

    Private Sub btnBuscCliente_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btBuscarCliente.Click

        codVenta = 0
        codCompra = 0
        txtFactura.Text = ""

        frmBusCliente = New frmClienteBuscador
        frmBusCliente.ShowDialog()
        txtCliente.Text = frmBusCliente.ClienteDesc
        codCliente = frmBusCliente.codCliente

        If codCliente > 0 Then
            btnBuscMercaderia.Focus()
        End If

    End Sub

    Private Sub btnBuscMercaderia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscMercaderia.Click

        If codCliente > 0 Or codProveedor > 0 Then

            frmBusMercaderia = New frmMercaderiaBuscador

            frmBusMercaderia.esDevolucion = True
            frmBusMercaderia.codVenta = codVenta
            frmBusMercaderia.codCompra = codCompra

            If codCliente > 0 Then
                frmBusMercaderia.esVenta = False
            ElseIf codProveedor > 0 Then
                frmBusMercaderia.esVenta = True
            End If

            frmBusMercaderia.ShowDialog()
            txtMercaderia.Text = frmBusMercaderia.MercaderiaDesc
            codMercaderia = frmBusMercaderia.codMercaderia
            codMercaderiaLote = frmBusMercaderia.codMercaderiaLote

            If codMercaderia > 0 Then
                txtcantidad.Focus()
            End If

        Else

        End If

    End Sub

    Private Sub txtcantidad_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcantidad.Leave
        If IsNumeric(txtcantidad.Text) Then

        End If
    End Sub

    Private Sub CargarNotasRemisionDetalle()
        Try

            codMercaderia = 0
            codMercaderiaDetalle = 0
            txtMercaderia.Text = ""
            txtLote.Text = ""
            cbxVto.Checked = False
            txtcantidad.Text = 1

            Dim ds As New DataTable
            ds = controller.get_NotasRemision_Detalles_All(oiml.dbConn, codNotaRemision)

            If Not ds Is Nothing Then
                dgvdetalle.DataSource = ds
                cboMotivo.Enabled = False
                btnSeleccionFactura.Enabled = False
            Else
                dgvdetalle.DataSource = Nothing
                cboMotivo.Enabled = True
                btnSeleccionFactura.Enabled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Dim ci As CultureInfo

    Private Sub CargarNotasRemision()
        Try
            If codNotaRemision > 0 Then

                Dim ds As New DataTable
                ds = controller.get_Remision_ByID(oiml.dbConn, codNotaRemision)

                If Not ds Is Nothing Then

                    txtActualizadoFecha.Text = ds.Rows(0)("actualizadoFecha_")
                    txtActualizadoPor.Text = ds.Rows(0)("usuario")

                    If ds.Rows(0)("idCliente").ToString() <> "" Then

                        txtCliente.Text = ds.Rows(0)("cliente")
                        codCliente = ds.Rows(0)("idCliente")

                    Else

                        txtProveedor.Text = ds.Rows(0)("proveedor")
                        codProveedor = ds.Rows(0)("idProveedor")

                    End If

                    nroRemision.Text = ds.Rows(0)("nroComprobante")
                    fechaFactura.Value = ds.Rows(0)("fecha")
                    cboEstado.Text = ds.Rows(0)("estado")

                    cboMotivo.SelectedValue = ds.Rows(0)("idMotivoStock")

                    CargarNotasRemisionDetalle()
                    ControlEstados()

                    If ds.Rows(0)("nroVenta").ToString() <> "" Then
                        txtFactura.Text = ds.Rows(0)("nroVenta")
                        codVenta = ds.Rows(0)("idVenta")
                    ElseIf ds.Rows(0)("nroCompra").ToString() <> "" Then
                        txtFactura.Text = ds.Rows(0)("nroCompra")
                        codCompra = ds.Rows(0)("idCompra")
                    End If

                End If

            Else
                cboEstado.Text = "EN PROCESO"
                nroRemision.Focus()

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub ControlEstados()

        If cboEstado.Text = "APROBADA" Then

            nroRemision.Enabled = False
            fechaFactura.Enabled = False
            fechaVto.Enabled = False
            cboMotivo.Enabled = False

            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False
            btBuscarCliente.Enabled = False

            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False

            btnEliminar.Enabled = False
            btnEliminarDetalle.Enabled = False

            btnConfirmar.Visible = False
            txtLote.Enabled = False
            cbxVto.Enabled = False
            cbxVto.Checked = False
            cboDeposito.Enabled = False

            txtcantidad.Enabled = False
            btnSeleccionFactura.Enabled = False

            btnCancelar.Focus()


        ElseIf cboEstado.Text = "ANULADA" Then

            nroRemision.Enabled = False
            fechaFactura.Enabled = False
            fechaVto.Enabled = False
            cboMotivo.Enabled = False

            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False
            btBuscarCliente.Enabled = False

            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False
            btnEliminarDetalle.Enabled = False

            btnConfirmar.Enabled = False
            txtLote.Enabled = False
            cbxVto.Enabled = False
            cbxVto.Checked = False
            cboDeposito.Enabled = False

            btnEliminar.Enabled = False
            btnAnular.Enabled = False

            txtcantidad.Enabled = False
            btnSeleccionFactura.Enabled = False

            btnCancelar.Focus()

        End If

    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        If nroRemision.Text = "" Then
            ErrorProvider1.SetError(nroRemision, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(nroRemision, "")
        End If        '

        If cboMotivo.Text.Contains("CLIENTE") Then

            If txtCliente.Text = "" Or codCliente = 0 Then
                ErrorProvider1.SetError(txtCliente, "Campo obligatorio")
                controlCampos = True
            Else
                ErrorProvider1.SetError(txtCliente, "")
            End If        '

        Else

            If txtProveedor.Text = "" Or codProveedor = 0 Then
                ErrorProvider1.SetError(txtProveedor, "Campo obligatorio")
                controlCampos = True
            Else
                ErrorProvider1.SetError(txtProveedor, "")
            End If        '

        End If
        

        Return controlCampos

    End Function

    Private Function ValidarCamposDetalle() As Boolean

        Dim controlCampos As Boolean = False

        If txtMercaderia.Text = "" Then
            ErrorProvider1.SetError(txtMercaderia, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtMercaderia, "")
        End If        '

        If txtcantidad.Text = "" Or Not IsNumeric(txtcantidad.Text) Then
            ErrorProvider1.SetError(txtcantidad, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtcantidad, "")
        End If        '

        'If txtprecio.Text = "" Or Not IsNumeric(txtprecio.Text) Then
        '    ErrorProvider1.SetError(txtprecio, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider1.SetError(txtprecio, "")
        'End If        '

        Return controlCampos

    End Function

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminar.Click
        If codNotaRemision > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Remisiones", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_Remision(oiml.dbConn, codNotaRemision, oiml.idUsuario) Then
                    Me.Close()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click

        If ValidarCampos() Then
            Exit Sub
        End If

        If codNotaRemision = 0 Then
            codNotaRemision = controller.Insert_Remision(oiml.dbConn, nroRemision.Text, fechaFactura.Value, codVenta, codCompra, Integer.Parse(cboMotivo.SelectedValue), cboEstado.Text, oiml.idUsuario, codCliente, codProveedor, 0, 0)

            If codNotaRemision > 0 Then

                CargarNotasRemision()
                MessageBox.Show("Registro grabado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_Remision(oiml.dbConn, codNotaRemision, nroRemision.Text, fechaFactura.Value, codVenta, codCompra, Integer.Parse(cboMotivo.SelectedValue), cboEstado.Text, oiml.idUsuario, codCliente, codProveedor, 0, 0) Then

                CargarNotasRemision()
                MessageBox.Show("Registro grabado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)


            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub dgvdetalle_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvdetalle.KeyDown
        If e.KeyCode = Keys.Enter Then
            If dgvdetalle.SelectedRows.Count > 0 Then

                codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If
        End If
    End Sub

    Private Sub dgvdetalle_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvdetalle.DoubleClick
        If dgvdetalle.SelectedRows.Count > 0 Then

            codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

        End If
    End Sub

    Private Sub dgvdetalle_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellClick
        Try

            If dgvdetalle.SelectedRows.Count > 0 Then

                codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnEliminarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminarDetalle.Click

        If codMercaderiaDetalle > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Remisiones", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_NotasRemision_Detalle(oiml.dbConn, codMercaderiaDetalle, oiml.idUsuario, codNotaRemision, cboMotivo.SelectedValue) Then
                    CargarNotasRemision()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnAgregarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDetalle.Click

        If ValidarCamposDetalle() Then
            Exit Sub
        End If

        Dim vtoLote As String = ""
        If cbxVto.Checked Then
            vtoLote = fechaVto.Value
        End If

        If codNotaRemision = 0 Then
            codNotaRemision = controller.Insert_Remision(oiml.dbConn, nroRemision.Text, fechaFactura.Value, codVenta, codCompra, Integer.Parse(cboMotivo.SelectedValue), cboEstado.Text, oiml.idUsuario, codCliente, codProveedor, 0, 0)

        Else

            If controller.Update_Remision(oiml.dbConn, codNotaRemision, nroRemision.Text, fechaFactura.Value, codVenta, codCompra, Integer.Parse(cboMotivo.SelectedValue), cboEstado.Text, oiml.idUsuario, codCliente, codProveedor, 0, 0) Then

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

        If codNotaRemision > 0 And codMercaderia > 0 Then

            If controller.Insert_NotasRemision_Detalle(oiml.dbConn, codNotaRemision, codMercaderia, _
                                                       Integer.Parse(txtcantidad.Text), txtLote.Text, vtoLote, _
                                                       cboDeposito.SelectedValue, cboMotivo.SelectedValue, _
                                                       codMercaderiaLote, codCompra, codVenta) Then
                CargarNotasRemision()
                MessageBox.Show("Registro grabado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    'Private Sub btnAnular_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnular.Click
    '    If codCompra > 0 Then
    '        If MessageBox.Show("Desea anular el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

    '            If controller.Update_Compras_Estado(oiml.dbConn, codCompra, "ANULADA", oiml.idUsuario) Then
    '                Me.Close()

    '            Else
    '                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

    '            End If

    '        End If
    '    End If
    'End Sub

    Private Sub cbxVto_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        fechaVto.Enabled = cbxVto.Checked
    End Sub

    Private Sub btnBuscOrdenCompra_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub btnConfirmar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirmar.Click
        If codNotaRemision > 0 Then

            nroRemision.Text = controller.get_Remisiones_Documento(oiml.dbConn, "REMISION", oiml.idUsuario)

            If controller.Update_Remisiones_Estado(oiml.dbConn, codNotaRemision, "APROBADA", oiml.idUsuario, nroRemision.Text) Then
                CargarNotasRemision()
                MessageBox.Show("Registro confirmado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub cboMotivo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboMotivo.SelectedIndexChanged

        If cboMotivo.Text.Contains("CLIENTE") Then
            btnBuscProveedor.Enabled = False
            btBuscarCliente.Enabled = True
            codProveedor = 0
            txtProveedor.Text = ""
        Else
            btnBuscProveedor.Enabled = True
            btBuscarCliente.Enabled = False
            codCliente = 0
            txtCliente.Text = ""
        End If

        codVenta = 0
        codCompra = 0
        txtFactura.Text = ""

    End Sub

    Private m_frmBusFactura As frmFacturaBuscador
    Public Property frmBusFactura() As frmFacturaBuscador
        Get
            Return m_frmBusFactura
        End Get
        Set(ByVal value As frmFacturaBuscador)
            m_frmBusFactura = value
        End Set
    End Property

    Private Sub btnSeleccionFactura_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSeleccionFactura.Click

        frmBusFactura = New frmFacturaBuscador
        frmBusFactura.conSaldo = False
        frmBusFactura.esDevolucion = True
        frmBusFactura.codVenta = 0
        frmBusFactura.codCompra = 0

        If codProveedor > 0 Then
            frmBusFactura.esCompra = True
            frmBusFactura.codCliente = codProveedor
        ElseIf codCliente > 0 Then
            frmBusFactura.esCompra = False
            frmBusFactura.codCliente = codCliente
        Else
            Return
        End If

        If frmBusFactura.ShowDialog() = Windows.Forms.DialogResult.OK Then

            codCompra = frmBusFactura.codCompra
            codVenta = frmBusFactura.codVenta

            Dim dt As New DataTable

            If codCompra > 0 Then

                dt = controller.get_Compras_ByID(oiml.dbConn, codCompra)
                If Not dt Is Nothing Then
                    codCompra = dt.Rows(0)("idCompra")
                    txtFactura.Text = dt.Rows(0)("nroComprobante")
                Else
                    MessageBox.Show("No se registran datos de la factura ingresada. Favor verifique la cuenta del proveedor.", "Informe", MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If

            Else

                dt = controllerVtas.get_Ventas_ByID(oiml.dbConn, codVenta)
                If Not dt Is Nothing Then

                    'Dim dtMercaControl As New DataTable
                    'dtMercaControl = controllerVtas.get_Ventas_Detalles_Devolucion(oiml.dbConn, codVenta)

                    'If Not dtMercaControl Is Nothing Then
                    codVenta = dt.Rows(0)("idVenta")
                    txtFactura.Text = dt.Rows(0)("nroComprobante")
                    'Else
                    'MessageBox.Show("La factura seleccionada no posee, mercaderias para devolver.", "Informe", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    'End If

                Else
                    MessageBox.Show("No se registran datos de la factura ingresada. Favor verifique la cuenta del proveedor.", "Informe", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            End If

        End If

    End Sub

End Class